package pro.team.utils.validator;

import pro.team.exception.RException;
import pro.team.utils.R;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 * see: https://blog.csdn.net/danielzhou888/article/details/74740817
 * see: https://docs.jboss.org/hibernate/validator/4.3/reference/zh-CN/html/
 * see: https://docs.jboss.org/hibernate/validator/6.1/reference/en-US/html_single/
 * @author liuxiaowei
 * @date 2020/11/5 16:47
 */
public class ValidatorUtils {

	//private static Logger log = LoggerFactory.getLogger(ValidatorUtils.class);

	private static Validator validator;

	static {
		validator = Validation.buildDefaultValidatorFactory().getValidator();
	}

	/**
	 * 校验对象
	 * 
	 * @param object 待校验对象
	 * @param groups 待校验的组
	 * @throws RException 校验不通过，则报RRException异常
	 */
	public static void validateEntity(Object object, Class<?>... groups) throws RException {
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
		if (!constraintViolations.isEmpty()) {
			ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
			//log.error(constraint.getMessage());
			throw new RException(constraint.getMessage());
		}
	}

	/**
	 * 校验对象
	 *
	 * @param object 待校验对象
	 * @param groups 待校验的组
	 * @return 返回 R 对象
	 */
	public static R validateEntityRes(Object object, Class<?>... groups){
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
		if (!constraintViolations.isEmpty()) {
			ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
			//log.error(constraint.getMessage());
			return R.error(constraint.getMessage());
		}
		return R.ok();
	}
}
